package org.ilovecode.display 
{
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import gs.TweenLite;
	import org.ilovecode.events.MenuEvent;
	
	/**
	 * ...
	 * @author Vjekoslav Ratkajec
	 */
	public class DropdownMenu extends MovieClip {
		
		private var contentMask:MovieClip;
		
		private var yHide:Number = -128;
		private var yReveal:Number = 0;
		private var duration:Number = 0.5;
		
		private var isMouseOverWindow:Boolean = false;
		private var isMouseOverItem:Boolean = false;
		private var activated:Boolean = false;
		
		private var timer:Timer;
		private var extention:DropdownMenu;
		
		public function DropdownMenu() {
			//init();
		}
		
		protected function init(menuMask:MovieClip, extention:DropdownMenu = null):void {
			contentMask = menuMask;
			contentMask.mouseEnabled = false;
			this.extention = extention;
			initListeners();
			
			timer = new Timer(500);
			timer.addEventListener(TimerEvent.TIMER, timerTick);
		}
		
		private function initListeners():void {
			this.addEventListener(MouseEvent.MOUSE_OVER, mouseOver);
			this.addEventListener(MouseEvent.MOUSE_OUT, mouseOut);
		}
		
		protected function addListenerToMenuItem(item:MenuItem):void {
			item.addEventListener(MouseEvent.MOUSE_OVER, itemMouseOver);
			item.addEventListener(MouseEvent.MOUSE_OUT, itemMouseOut);
			item.addEventListener(MouseEvent.CLICK, itemClick);
		}
		
		protected function itemClick(event:MouseEvent):void {
			var name:String = String(event.currentTarget.name).replace("Button", "");
			this.dispatchEvent(new MenuEvent(MenuEvent.CLICK, name));
		}
		
		protected function itemMouseOver(event:MouseEvent):void {
			MenuItem(event.currentTarget).animateMouseOver();
			isMouseOverItem = true;
		}
		
		protected function itemMouseOut(event:MouseEvent):void {
			MenuItem(event.currentTarget).animateMouseOut();
			isMouseOverItem = false;
		}
		
		private function mouseOver(event:MouseEvent):void {
			isMouseOverWindow = true;
		}
		
		private function mouseOut(event:MouseEvent):void {
			isMouseOverWindow = false;
		}
		
		private function timerTick(event:TimerEvent):void {
			if (isActive) {
				activated = true;
			}
			
			if (!isActive && activated ) {
				hide();
				activated = false;
				this.dispatchEvent(new Event(Event.DEACTIVATE));
			}
		}
		
		public function get isActive():Boolean {
			var extentionFlag:Boolean = false;
			if (extention != null) {
				extentionFlag = extention.isActive;
			}
			
			if (isMouseOverItem || isMouseOverWindow || extentionFlag) return true;
			
			return false;
		}
		
		public function show():void {
			TweenLite.to(contentMask, duration, { y:yReveal } );
			timer.start();
		}
		
		public function hide():void {
			TweenLite.to(contentMask, duration, { y:yHide } );
			timer.stop();
		}
		
	}

}